
import os
import logging
import psycopg2
import psycopg2.extras
from flask import Flask
from flask import g
from flask import request
from flask import jsonify
from flask_cors import CORS
from database import PostgreSingleton
from database.wx_token_table_methods import WxTokenTableMethods
from flask_blueprint.wx_login_blueprint import wx_login_blueprint
from flask_blueprint.user_info_extend_blueprint import user_info_extend_blueprint
from flask_blueprint.srm_blueprint import static_resource_bp
from flask_blueprint.wx_authentication_blueprint import wx_authentication_blueprint
from flask_blueprint.web_login_blueprint import web_login_blueprint

app = Flask(__name__)

logger = logging.getLogger(__name__)


# init database
with PostgreSingleton() as conn:
    script_path = "database/init_db.sql"  
    logger.info(os.path.exists(script_path))
    if os.path.exists(script_path):
        logger.info("init database from script")
        with open(script_path, 'r', encoding='utf-8') as file:
            cur = conn.cursor()
            sql_script = file.read()
            cur.execute(sql_script)
            conn.commit()  # 提交事务
    

app.logger.setLevel(logging.DEBUG)
app.register_blueprint(wx_login_blueprint)
app.register_blueprint(user_info_extend_blueprint)
app.register_blueprint(static_resource_bp)
app.register_blueprint(wx_authentication_blueprint)
app.register_blueprint(web_login_blueprint)


CORS(app)

no_auth_required_routes = [
    '/',
    '/tt_login',
    '/tt_get_user_phone',
    '/files',
    '/tt/api/generate_share_qr_code',
    '/web_login',

]

@app.before_request
def before_request():

    if request.path not in no_auth_required_routes and not request.path.startswith('/view/'):
        # check if token is present in the request header

        token = request.headers.get('Authorization') # 如果微信不让你用Authorization，可以用token来代替

        if not token:

            token = request.headers.get('token')

        if not token:

            token = request.args.get('token') # 如果微信不让你用Header方式，可以用传参方式来代替

        if not token:
            return jsonify({
                "status": -1,
                "errorCode": 1,
                "errorMsg": "Token is missing in the request header",
                "resultBody": None
            })
        

        # verify token here

        if token == "root": # 这里设置一个超级管理员的token，用来测试接口是否正常

            g.wx_user_id = 1 # 设置超级管理员的user_id
                
        else:
            with PostgreSingleton() as conn:

                cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

                wx_token_table_methods = WxTokenTableMethods(conn, cur)

                # 查询连接是否/web/ 开头，如

                # /web/login
                # /web/register

                # if request.path.startswith('/web/'):
                #     verify_token_result = wx_token_table_methods.verify_token(token, "web_login")
                    
                # else:
                #     verify_token_result = wx_token_table_methods.verify_token(token)

                verify_token_result = wx_token_table_methods.verify_token(token)

                if not verify_token_result:

                    verify_token_result = wx_token_table_methods.verify_token(token, "web_login") # 尝试web_login的token

                if not verify_token_result:

                    return jsonify({
                        "status": -1,
                        "errorCode": 2,
                        "errorMsg": "Token is invalid",
                        "resultBody": None
                    })

                g.wx_user_id = verify_token_result['user_id']
            
    app.logger.debug('before_request')


# @app.after_request
# def after_request(response):
#     app.logger.debug('after_request')
#     return response


# @app.teardown_request
# def teardown_request(exception):
#     app.logger.debug('teardown_request')

#     return exception




if __name__ == '__main__':
    
    app.run(debug=True, port=5200)
    
    # /root/python3env/venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 main:app




